package cn.iocoder.yudao.framework.common.util.sign;

import cn.iocoder.yudao.framework.common.exception.ServerException;
import com.google.common.base.Joiner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.TreeMap;

public class SignUtil {

//    //todo 从配置文件中读取,有业务人员提供
//    @Value("${jdApi.appSecret}")
//    static String appSecret;
    public static final String  appSecret="E24F9226C9D71D57F5";
    /**
     * vo参数key排序，返回treemap.
     *
     * @param o 请求参数vo
     * @return 返回treemap
     */
    public static Map<String, Object> convertToTreeMap(Object o) {
        Field[] declaredFields = o.getClass().getDeclaredFields();
        Map<String, Object> treeMap = new TreeMap<>();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            try {
                String fieldName = field.getName();
                Object fieldValue = field.get(o);
                //sign和signType不作为密文参数
                if (fieldName.equals("sign")||fieldName.equals("signType")) {
                    continue;
                }
                //如果某个变量没有值时，那么该变量的key和value对将不出现在请求的加密明文中
                if (fieldValue != null && !"".equals(fieldValue)) {
                    treeMap.put(fieldName, fieldValue);
                }
            } catch (IllegalAccessException e) {
                throw new ServerException(500,"对象转map异常");
            }
        }
        return treeMap;
    }

    /**
     *  给参数加密.
     *
     * @param map key排序后的treemap
     * @return 返回md加密后的串
     */
    public static String buildSignature(Map<String, Object> map ) {
        String paramsStr = Joiner.on("").withKeyValueSeparator("").join(map);
        //最后组合成的待加密明文应无空格，所有空白字符，添加appSecret
        String text = (paramsStr + appSecret).replaceAll(" +", "");
        System.out.println(text);
        String ciphertext = DigestUtils.md5DigestAsHex(text.getBytes());
        System.err.println(ciphertext);
        return ciphertext;
    }
}
